package edu.biwu.servlet;

import edu.biwu.bean.User;
import edu.biwu.utils.JDBCUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    //1.获取浏览器发送的参数
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"  "+password);

   //2.利用DbUtils以及页面传递的username和password去数据库查询
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        User user = null;
        try {
            user = qr.query("SELECT*FROM `user`WHERE username=?AND `password`=?",
                    new BeanHandler<>(User.class),
                    username,
                    password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    //根据user来判断最终结果
    //a.如果user为null,说明在数据库中没有查询到该用户,反馈给浏览器login fail
    //b.如果user不为null,说明在数据库中查询到了该用户,反馈给浏览器login success
        if (user == null) {
            response.getWriter().write("login fail");
        } else {
            response.getWriter().write("login success");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
